﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace GTA
{
    public partial class FrmTaskStatesManagement : BaseForm
    {
        #region Local Objects
        private List<BusinessEntity.TaskDomain> states;
        #endregion

        #region Starting Form
        public FrmTaskStatesManagement()
        {
            InitializeComponent();
        }
        private void FrmTaskStatesManagement_Load(object sender, EventArgs e)
        {
            StartForm();
        }
        private void StartForm()
        {
            try
            {
                LoadCurrentStates();
                LoadTeamSystemStates();
            }
            catch (Exception ex)
            {
                HandleException("Inicializar a tela.", ex);
            }
        }
        #endregion

        #region Events
        private void lstStatesTeamSystem_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            SortList(lstStatesTeamSystem, OrdenacaoListView.Tipo.Alfabetica, ref columnOrder, ref sortOrder, e.Column);
        }
        private void lstStatesTeamSystem_Resize(object sender, EventArgs e)
        {
            lstStatesTeamSystem.Columns[0].Width = lstStatesTeamSystem.Width - lstStatesTeamSystem.Columns[1].Width - 20;
        }
        private void lstStates_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            SortList(lstStates, OrdenacaoListView.Tipo.Alfabetica, ref columnOrder, ref sortOrder, e.Column);
        }
        private void lstStates_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                RemoveSelectedStates();
        }
        private void lstStates_Resize(object sender, EventArgs e)
        {
            lstStates.Columns[0].Width = lstStates.Width - lstStates.Columns[1].Width - 20;
        }
        private void cmdImport_Click(object sender, EventArgs e)
        {
            ImportStates();
        }
        private void cmdClean_Click(object sender, EventArgs e)
        {
            CleanTeamSystemStatesSelection();
        }
        private void cmdRemove_Click(object sender, EventArgs e)
        {
            RemoveSelectedStates();
        }
        private void importarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImportStates();
        }
        private void limparToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CleanTeamSystemStatesSelection();
        }
        private void removerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RemoveSelectedStates();
        }
        #endregion

        #region Methods
        private void EnableControlAssync(Control ctrl, bool state)
        {
            if (ctrl.InvokeRequired)
                ctrl.Invoke(new Action<Control, bool>(EnableControlAssync), new Object[] { ctrl, state });
            else
                ctrl.Enabled = state;
        }
        private void BindStateListAssync(ListView list, List<BusinessEntity.TaskDomain> source)
        {
            if (list.InvokeRequired)
                list.Invoke(new Action<ListView, List<BusinessEntity.TaskDomain>>(BindStateListAssync), new Object[] { list, source });
            else
            {
                list.Items.Clear();
                if (source != null)
                {
                    foreach (BusinessEntity.TaskDomain item in source)
                    {
                        ListViewItem listItem = new ListViewItem(item.Description);
                        listItem.SubItems.Add(item.ID.ToString());
                        list.Items.Add(listItem);
                    }
                }
            }
        }
        private void LoadTeamSystemStates()
        {
            Thread trd = new Thread(new ThreadStart(LoadTeamSystemStatesAssync));
            trd.Start();
        }
        private void LoadTeamSystemStatesAssync()
        {
            try
            {
                EnableControlAssync(lstStatesTeamSystem, false);
                EnableControlAssync(cmdImport, false);
                EnableControlAssync(cmdClean, false);
                List<BusinessEntity.TaskDomain> cleanList = new List<GTA.BusinessEntity.TaskDomain>();
                cleanList.Add(new GTA.BusinessEntity.TaskDomain(0, "Carregando Lista"));
                BindStateListAssync(lstStatesTeamSystem, cleanList);

                List<BusinessEntity.TaskDomain> statesTeamSystem = new BusinessLogic.GTA().ListStatesTeamSystem(Program.LoggedUser);
                if (states != null && states.Count > 0)
                    statesTeamSystem.RemoveAll(it => states.Exists(itState => it.Description.CompareTo(itState.Description) == 0));
                BindStateListAssync(lstStatesTeamSystem, statesTeamSystem);
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de categorias do TeamSystem.", ex);
            }
            finally
            {
                EnableControlAssync(lstStatesTeamSystem, true);
                EnableControlAssync(cmdImport, true);
                EnableControlAssync(cmdClean, true);
            }
        }
        private void LoadCurrentStates()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                states = new BusinessLogic.GTA().ListStates();
                BindStateList(states, lstStates);
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de Status da Base de Dados.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void BindStateList(List<GTA.BusinessEntity.TaskDomain> statesList, ListView lstStates)
        {
            lstStates.Items.Clear();
            if (statesList != null && statesList.Count > 0)
            {
                foreach (BusinessEntity.TaskDomain itemState in statesList)
                {
                    ListViewItem listItem = new ListViewItem(itemState.Description);
                    listItem.SubItems.Add(itemState.ID.ToString());
                    lstStates.Items.Add(listItem);
                }
            }
        }
        private void ImportStates()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (lstStatesTeamSystem.CheckedItems.Count > 0)
                {
                    List<BusinessEntity.TaskDomain> importStates = new List<BusinessEntity.TaskDomain>();
                    foreach (ListViewItem listItem in lstStatesTeamSystem.CheckedItems)
                        importStates.Add(new GTA.BusinessEntity.TaskDomain()
                        {
                            Description = listItem.SubItems[0].Text
                        });
                    new BusinessLogic.GTA().SaveStates(importStates);
                    MessageBox.Show("Categorias importadas com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadCurrentStates();
                    LoadTeamSystemStates();
                    MainForm.BuildInformativeSummaryContextMenuFilters();
                }
                else
                    MessageBox.Show("Selecione ao menos uma categoria do TeamSystem para importar!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Importar as categorias do TeamSystem.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void CleanTeamSystemStatesSelection()
        {
            try
            {
                while (lstStatesTeamSystem.CheckedItems.Count > 0)
                    lstStatesTeamSystem.CheckedItems[0].Checked = false;
            }
            catch (Exception ex)
            {
                HandleException("Limpar a seleção de categorias da lista do TeamSystem", ex);
            }
        }
        private void RemoveSelectedStates()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (lstStates.SelectedItems.Count > 0)
                {
                    if (MessageBox.Show("Deseja realmente remover as categorias selecionadas?\r\nEstas não estarão mais disponíveis para pesquisas de tarefas.", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        BusinessLogic.GTA bl = new BusinessLogic.GTA();
                        foreach (ListViewItem listItem in lstStates.SelectedItems)
                            bl.DeleteState(Convert.ToInt32(listItem.SubItems[1].Text));
                        MessageBox.Show("Categorias removidas com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadCurrentStates();
                        LoadTeamSystemStates();
                        MainForm.BuildInformativeSummaryContextMenuFilters();
                    }
                }
                else
                    MessageBox.Show("Selecione ao menos uma categoria da Base de Dados para remover!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Remover as categorias selecionadas da base de dados", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        #endregion
    }
}
